const express = require("express");
const puppeteer = require("puppeteer");
const ejs = require("ejs");
const FormData = require("form-data");
const fs = require("fs");
const path = require("path");
const marked = require("marked");
const axios = require("axios");
const { config } = require("./config");

const app = express();
app.use(express.static(path.join(__dirname, "images")));
app.set("view engine", "ejs");
app.use(express.json());
const port = 3000;

// import { getUseUuid, strRandomHandle } from '@/utils'
const { convertImagesToBase64, saveImage } = require("./utils/index");

let imagePathList = [
  "bpai.png",
  "code.png",
  "consult.png",
  "foot-bg.png",
  "zx-answer.png",
  "zx-question.png",
];
let base64Obj = convertImagesToBase64(imagePathList);

// 假设这是获取消息的函数
async function getMessagesByIds(postData, authorization) {
  // 这里应该是从数据库或其他服务获取消息

  try {
    // console.log("token---", token);
    // 发起 GET 请求
    const response = await axios.post(
      `${config.server}/eims/BPai/wechat/getContentByShareId`,
      postData,
      {
        headers: {
          authorization,
          //   'Content-Type': 'application/json'
        },
      }
    );
    console.log("response--", response);
    // 处理响应数据

    return response.data;
  } catch (error) {
    console.error("Error fetching data:", error);

  }
}

function processMessages(messages) {
  if (!messages || !messages.length) return [];

  return messages.map((item) => {
    let recordContent = item.recordContent
      ? JSON.parse(item.recordContent)
      : {};
    recordContent.contextMsg = recordContent.contextMsg.replace(/\\n/g, "\r\n");

    return {
      ...recordContent,
      ...item,
      status: "done",
      recommend: [],
      message: recordContent.contextMsg,
      type: recordContent.direction === "Q" ? "send" : "receive",
    };
  });
}

async function getCode(shareId, authorization) {
  try {
    let postData = {
      scene: `shareId=${shareId}`, // 替换为实际的 scene 参数
      page: "pages/chat/list", // 替换为实际的页面路径
      envVersion: config.env === "prod" ? "release" : "trial", // 体验版
      // checkPath: true, // 替换为实际的页面路径
    };
    const response = await axios.post(
      `${config.server}/portal/enterprise/taxes/user/getUnlimitedQRCode`,
      postData,
      {
        headers: {
          authorization,
          //   'Content-Type': 'application/json'
        },
      }
    );
    console.log("response--", response);
    return response.data.result.code;
    // throw Error('二维码生成失败')
  } catch (err) {
    console.log("err", err);
    // res.status(500).json({
    //   success: false,
    //   message: "Error fetching data",
    //   error: err.message, // 你也可以返回更多的错误信息
    // });
  }
}

app.post("/generate-image", async (req, res) => {
  try {
    const {  shareId, mobile,type = 1 } = req.body;
    const { authorization } = req.headers;
    console.log("req.header--", req);
    console.log("req.header1--", req.headers);
    const codeImg = await getCode(shareId, authorization);
    console.log("codeImg--", codeImg);
    const { result } = await getMessagesByIds(
      {
        shareId,
      },
      authorization
    );
    const query = {
      mobile,
    };
    // 转换对话列表
    let list = processMessages(result.list);
    let templateContent = type == 1 ? 'template.ejs' : 'imgTemplate.ejs'
    // 渲染模板
    const htmlContent = ejs.render(
      // fs.readFileSync(path.join(__dirname, "template", "cover.ejs"), "utf8"),
      
      fs.readFileSync(path.join(__dirname, "template", templateContent), "utf8"),
      { messages: list, query, marked: marked.marked, base64Obj, codeImg }
    );
    // 启动浏览器
    const browser = await puppeteer.launch({
      headless: true,
      // executablePath: '/usr/bin/chromium-browser'
      // devtools: true, // 启用 DevTools
      args: ['--no-sandbox']
    });

    const page = await browser.newPage();

    // 设置页面内容
    await page.setContent(htmlContent, { waitUntil: "load" });
    // await new Promise((resolve) => setTimeout(resolve, 1000));
    // 等待特定元素加载
    await page.waitForSelector(".chat-box");
    // 获取根字体大小
    let rootFontSize = 100
    console.log('rootFontSize--',rootFontSize);
    
    await page.evaluate((type) => {
      rootFontSize = parseFloat(getComputedStyle(document.documentElement).fontSize);
      if(type != 1){
      // 在这里执行需要的 JavaScript 代码
      const contentDiv = document.getElementById("content");
      const elements = document.querySelectorAll(".chat-content > div");

      if (elements.length) {
        // 初始化总高度
        let totalHeight = 0;
        console.log('rootFontSize333--',rootFontSize);
        // 使用 for 循环进行遍历，并在高度超过 3000 时停止
        const heightRem = 3500 / 50; // rem
        const heightPx = heightRem * rootFontSize;
        console.log("heightPx--", heightPx);
        for (let i = 0; i < elements.length; i++) {

          const computedStyle = window.getComputedStyle(elements[i]);
          console.log("computedStyle--", computedStyle);
          const height = computedStyle.height; // 获取实际高度
          // const rect = elements[i].getBoundingClientRect();
          // console.log('rect--',rect);
          // const height = rect.height; // 获取实际高度
          console.log("height11--", height);
          totalHeight += height;

          // 如果总高度超过 3000，停止遍历
          if (totalHeight > heightPx) {
            console.log("Total height exceeds heightPx:", totalHeight);
            contentDiv.classList.add("more-than");
            // 在此处处理对应逻辑，例如显示警告或截断内容
            break;
          }
        }

        if (totalHeight <= heightPx) {
          contentDiv.classList.remove("more-than");
          console.log("Total height is within limit:", totalHeight);
        }
      }
    }
    },type);
  
    // 计算视口大小
    const widthRem = 6.38; // rem
    const widthPx = widthRem * rootFontSize;

    // 选择特定元素
    const element = await page.$(".chat-box"); // 替换为您的选择器

    // 生成图片
    const imagePath = `path/to/image-${Date.now()}.png`;
    const boundingBox = await element.boundingBox();
    let url = "";
    if (element) {
      // 设置视图区域与内容宽度一致
      await page.setViewport({
        width: Math.ceil(widthPx),
        height: Math.ceil(boundingBox.height),
        deviceScaleFactor: 1,
      });
      const screenshotBuffer = await element.screenshot({
        omitBackground: true,
        type: "png",
      });
      let buffer = screenshotBuffer;

      console.log("screenshotBuffer---", buffer);
      if (!Buffer.isBuffer(buffer)) {
        buffer = Buffer.from(screenshotBuffer);
        // return;
      }

      const formData = new FormData();
      // 将 Buffer 添加到 FormData 中，作为文件上传

      // 将 Blob 添加到 FormData 对象，假设键名为 'image'
      formData.append("file", buffer, "image.jpeg");
      formData.append("fileType", "5");

      url = await uploadFile(formData);

      // 可选：保存截图到本地文件系统以便测试
      fs.writeFileSync('screenshot.png', screenshotBuffer);
    } else {
      console.error("Element not found");
    }

    console.log("url--", url);
    // saveImage(url);
    // 关闭浏览器
    await browser.close();

    // 返回图片路径
    res.json({ code: "200", message: "操作成功", result: { url } });
  } catch (error) {
    console.error("Error fetching data:", error);
    res.status(500).json({
      success: false,
      message: "Error fetching data",
      error: error.message, // 你也可以返回更多的错误信息
    });
  }
});

const uploadFile = (formData) => {
  return new Promise((resolve, reject) => {
    axios
      .post(`${config.server}/tenant/manager/package/uploadFile`, formData, {
        headers: {
          // authorization,
          "Content-Type": "multipart/form-data",
          "Client-Type": "mobile",
        },
      })
      .then((res) => {
        console.log("res--", res.data.result);
        resolve(res.data.result);
      })
      .catch((err) => {
        console.log("err----", err);
        reject(err);
      });
  });
};

app.listen(port, () => {
  console.log(`Server running at http://localhost:${port}`);
});
